package com.example.mybatisplusdemo.mapper;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.mybatisplusdemo.domain.Dog;
import com.example.mybatisplusdemo.domain.Persion;
import com.example.mybatisplusdemo.domain.po.User;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@SpringBootTest
@Slf4j
class MapperSelect {

    @Autowired
    private UserMapper userMaper;

    @Autowired
    private Persion persion;

    @Autowired
    private Dog dog;

    @Test
    void contextLoads() {

    }

    // 查询
    @Test
    void testSelectById(){
        // 查询id
        // SELECT id,name,age,email FROM user WHERE id=?
        User user = userMaper.selectById(4L);
        System.out.println(user);

    }

    @Test
    void testSelectBatchIds(){

        // 根据多个Id查询数据
        // SELECT id,name,age,email FROM user WHERE id IN ( ? , ? , ? , ? , ? )
        List<Long> longs = Arrays.asList(1L, 2L, 3L, 4L, 5L);
        List<User> users = userMaper.selectBatchIds(longs);
        System.out.println(users);

    }
    @Test
    void testSelectByMap(){

        // 根据Map对象查询数据
        // SELECT id,name,age,email FROM user WHERE name = ? AND email = ?
        Map<String, Object> map = new HashMap<>();
        map.put("name", "DUJUNHUI");
        map.put("email", "asdfasdf@123.com");
        List<User> users1 = userMaper.selectByMap(map);
        users1.forEach(System.out::println);


    }
    @Test
    void testSelectList(){

        // 查询
        // SELECT id,name,age,email FROM user
        List<User> users2 = userMaper.selectList(null);
        users2.forEach(System.out::println);

        // QueryWapper
        // SELECT id,name,age FROM user WHERE (name LIKE ? AND age >= ?)
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<User>()
                .select("id", "name", "age")
                .like("name", "D")
                .ge("age", 18);
        List<User> users3 = userMaper.selectList(userQueryWrapper);
        users3.forEach(System.out::println);

        // 避免sql字段的硬编码
        // LambdaQueryWrapper
        LambdaQueryWrapper lambdaQueryWrapper = new LambdaQueryWrapper<User>()
                .select(User::getId, User::getName, User::getAge)
                .like(User::getName, "D")
                .ge(User::getAge, 18);
        List<User> users4 = userMaper.selectList(userQueryWrapper);
        users4.forEach(System.out::println);

    }
}
